/**
 * Created by lijizhuang on 16/11/12.
 */
define(['jquery', 'underscore', 'backbone', 'common', 'url', 'text!modules/dashboard/modal/newReserveView.html', 'utils/regutil', 'extensions/stringExts', 'models/dashboard/customerIdType', 'models/dashboard/orderType', 'models/dashboard/channelType', 'models/dashboard/spendItemType', 'extensions/dateExts'],
    function ($, _, Backbone, Common, Url, NewReserveViewTemplate, RegUtil, StringExts, CustomerIdType, OrderType, ChannelType, SpendItemType, DateExts) {
        var newReserveView = Backbone.View.extend({
            tagName: 'div',
            id: 'newReserve',
            className: 'modal fade',
            template: _.template(NewReserveViewTemplate),

            initialize: function (attrs) {
                this.options = attrs;
                this.creatingOrder = false;
            },

            events: {
                'click #saveBtn': 'onSaveButtonClick',
                'click .customerItem .addCustomer': 'onAddCustomer',
                'click .customerItem .removeCustomer': 'onRemoveCustomer',
                'click .addIncome': 'onAddIncome',
                'click .removeCosts': 'onRemoveIncome',
                'focusin input': 'onTextboxFocus',
                'keyup input#roomCosts, .otherCosts': 'onRoomCostsEnter',
                'keyup .reserve-reserverInfo-item #reserveNotes': 'onReserveNotesEnter',
                'keyup #roomCostsNotes, .otherCostsNotes': 'onCostsNotesEnter'
            },

            onSaveButtonClick: function (e) {
                var valid_success = true;
                var _tempThis = this;

                var postModel = {};
                postModel.bnbId = this.model.bnbId;
                postModel.orderType = OrderType.BO;
                postModel.paymentType = this.$('#paymentType').val();
                postModel.fromDate = this.$('#fromDate').val();
                postModel.toDate = this.$('#toDate').val();
                var fDate = new Date(postModel.fromDate.replace(/-/g, "/"));
                var tDate = new Date(postModel.toDate.replace(/-/g, "/"));
                postModel.roomNights = fDate.diffInDays(tDate);
                postModel.channel = ChannelType.Offline; //dashboard里新建订单，默认是offline
                postModel.roomId = this.model.roomId;
                postModel.roomNumber = this.model.roomNumber;
                postModel.roomTypeId = this.model.roomTypeId;
                postModel.reserverUser = this.$('#reservePeople').val();
                postModel.reserverMobile = this.$('#reserveMobile').val();
                postModel.amount = this.$('.consumeSum div span:last').text();  //订单金额
                postModel.arrivalTime = this.$('#arrivalTime').val();
                postModel.orderNotes = this.$('#reserveNotes').val();
                postModel.customers = []; //入住人列表
                postModel.spendings = []; //费用列表

                var $reservePeople = $('.reserve-reserverInfo-item #reservePeople');
                if ($reservePeople.val().trim().length === 0) {
                    this.showError($reservePeople, '姓名不能为空', 'top');
                    valid_success = false;
                }
                else if (!RegUtil.chineseNameReg.test($reservePeople.val())) {
                    this.showError($reservePeople, '姓名格式错误', 'top');
                    valid_success = false;
                }
                else {
                    this.clearError($reservePeople);
                }

                var $reserveMobile = $('.reserve-reserverInfo-item #reserveMobile');
                if ($reserveMobile.val().trim().length === 0) {
                    this.showError($reserveMobile, '手机号不能为空', 'top');
                    valid_success = false;
                }
                else if (!RegUtil.mobileReg.test($reserveMobile.val())) {
                    this.showError($reserveMobile, '手机号格式错误', 'top');
                    valid_success = false;
                }
                else {
                    this.clearError($reserveMobile);
                }

                //var $customerName = $('.customerItem .customerName');
                //$customerName.each(function () {
                //    if ($(this).val().trim().length === 0) {
                //        _tempThis.showError($(this), '姓名不能为空')
                //    }
                //    else if (!RegUtil.chineseNameReg.test($customerName.val())) {
                //        _tempThis.showError($(this), '姓名格式错误', 'top');
                //        valid_success = false;
                //    }
                //    else {
                //        _tempThis.clearError($(this));
                //    }
                //});

                var $customerItems = $('.customerItem');
                $customerItems.each(function () {
                    var customer = {};

                    //获取入住人姓名
                    var $cusName = $(this).find('.customerName:first');
                    if ($cusName.val().trim().length === 0) {
                        _tempThis.showError($cusName, '姓名不能为空');
                        valid_success = false;
                    }
                    else if (!RegUtil.chineseNameReg.test($cusName.val())) {
                        _tempThis.showError($cusName, '姓名格式错误', 'top');
                        valid_success = false;
                    }
                    else {
                        customer.customerName = $cusName.val();
                        _tempThis.clearError($cusName);
                    }

                    //获取证件类型
                    var $idType = $(this).find('.customerIdType:first');
                    //当类型为身份证时
                    if ($idType.val() == CustomerIdType.IdCard) {
                        var $idCard = $(this).find('.customerIdNo:first');
                        if ($idCard.val().trim().length === 0) {
                            _tempThis.showError($idCard, '身份证号不能为空', 'top');
                            valid_success = false;
                        }
                        else if (!Common.isIdCard($idCard.val())) {
                            _tempThis.showError($idCard, '身份证号格式错误', 'top');
                            valid_success = false;
                        }
                        else {
                            customer.customerIdType = CustomerIdType.IdCard;
                            customer.customerIdNumber = $idCard.val();
                            _tempThis.clearError($idCard);
                        }
                    }

                    postModel.customers.push(customer);
                });

                var $roomPrice = $('.roomCostsItem #roomCosts');
                var roomPrice = parseFloat($roomPrice.val());
                if (!RegUtil.numberReg.test(roomPrice)) {
                    _tempThis.showError($roomPrice, '格式错误');
                    valid_success = false;
                }
                else {
                    var spending = {};
                    spending.spendType = SpendItemType.RoomFee;
                    spending.amount = roomPrice;
                    spending.notes = this.$('#roomCostsNotes').val().trim();
                    postModel.spendings.push(spending);

                    _tempThis.clearError($roomPrice);
                }

                var $otherCostsItem = $('.otherCostsItem').each(function () {
                    var $itemType = $(this).find('.otherCostsSelect:first');
                    var $itemPrice = $(this).find('.otherCosts:first');
                    var itemPrice = parseFloat($itemPrice.val());
                    var $itemNotes = $(this).find('.otherCostsNotes:first');

                    if (!RegUtil.numberReg.test(itemPrice)) {
                        _tempThis.showError($itemPrice, '格式错误');
                        valid_success = false;
                    }
                    else {
                        var spending = {};
                        spending.spendType = $itemType.val();
                        spending.amount = itemPrice;
                        spending.notes = $itemNotes.val().trim();
                        postModel.spendings.push(spending);

                        _tempThis.clearError($itemPrice);
                    }
                });

                //客户端验证通过
                if (valid_success) {
                    this.creatingOrder = true;
                    var $saveBtn = $(".new-reserve-footer #saveBtn");
                    $saveBtn.attr('disabled', "true");
                    $saveBtn.text('提交中..');

                    Common.sendAjaxRequest(Url.newOrder, postModel, _.bind(function (data) {
                        if (data && data.Content && data.Content.length > 0) {
                            //成功后
                            this.$el.modal('hide');

                            this.creatingOrder = false;
                            $saveBtn.attr('disabled', "false");
                            $saveBtn.text('保存');
                        }
                    }, this), _.bind(function (data) {
                        if (data && data.Content && data.Content.length > 0) {
                            this.creatingOrder = false;

                            //显示异常信息

                            $saveBtn.attr('disabled', "false");
                            $saveBtn.text('保存');
                        }

                    }, this), false);
                }
            },

            onReserveNotesEnter: function (e) {
                var notes = $(e.currentTarget).val().trim();

                if ($.trim(notes).gbLength() > 100) {
                    $(e.currentTarget).val(notes.substring(0, 100));
                }
            },

            onCostsNotesEnter: function (e) {
                var notes = $(e.currentTarget).val().trim();

                if ($.trim(notes).gbLength() > 50) {
                    $(e.currentTarget).val(notes.substring(0, 50));
                }
            },

            onRoomCostsEnter: function (e) {
                //得到并验证当前输入的价格
                var priceStr = $(e.currentTarget).val();
                var price = parseFloat(priceStr);

                //判断小数点后有几位
                if (priceStr.indexOf('.') >= 0) {
                    var digitLength = priceStr.split(".")[1].length;
                    if (digitLength > 2) {
                        $(e.currentTarget).val(parseFloat(priceStr).toFixed(2));
                    }
                }

                if (!RegUtil.numberReg.test(priceStr)) {
                    this.showError($(e.currentTarget), '异常数字');
                }
                else if (price < 1) {
                    $(e.currentTarget).val(1);

                    //金额总数变化
                    this.onUpdateAmount();
                }
                else if (price > 10000000) {
                    $(e.currentTarget).val(10000000);

                    //金额总数变化
                    this.onUpdateAmount();
                }
                else {
                    //验证通过
                    this.clearError($(e.currentTarget));

                    //金额总数变化
                    this.onUpdateAmount();
                }
            },

            onUpdateAmount: function (e) {
                //更新费用结果
                var totalAmount = 0;
                $('input#roomCosts, .otherCosts').each(function () {
                    var value = 0;
                    if ($(this).val() != '')
                        value = parseFloat($(this).val());
                    totalAmount += value;
                });
                this.$('.consumeSum div span:last').text(parseFloat(totalAmount).toFixed(2));
                this.$('.new-reserve-footer div span:last').text(parseFloat(totalAmount).toFixed(2));
            },

            onAddIncome: function (e) {
                //移除添加按钮
                $(e.currentTarget).remove();

                //增加一行
                var rowEle = '<div class="otherCostsItem"><span><select class="otherCostsSelect"> <option value="Deposit">押金</option> <option value="Activity">民宿活动</option> <option value="Others">其它</option></select> </span> <span style="position: relative"> <input type="text" class="otherCosts"> </span> <span> <input type="text" class="otherCostsNotes" placeholder="备注 (选填,限50个字符内)"> </span> <span class="removeCosts"></span> </div>';
                this.$('.consumeList').append($(rowEle));

                var lastChild = this.$('.consumeList').find('div:last');
                if (lastChild.find('.addIncome').length == 0) {
                    lastChild.append('<span class="addIncome"></span>');
                }

                //自动将滚动条滚到最后
                $(".reserve-body").scrollTop($(".reserve-body").get(0).scrollHeight);
            },

            onRemoveIncome: function (e) {
                this.$(e.currentTarget).parent().remove();

                var lastChild = this.$('.consumeList').find('div.otherCostsItem:last');

                if (lastChild.length === 0) {
                    lastChild = this.$('.consumeList').find('div.roomCostsItem:last');
                }

                if (lastChild.find('.addIncome').length == 0) {
                    lastChild.append('<span class="addIncome"></span>');
                }

                this.onUpdateAmount();
            },

            onRemoveCustomer: function (e) {
                //如果存在多行,那么可以移除一行,并且在末行的最后跟上添加按钮
                if (this.$('.customerItem').length > 1) {
                    $(e.currentTarget).parent().remove();
                    if (this.$('.customerItem:last').find('.addCustomer').length == 0) {
                        this.$('.customerItem:last').append('<span class="addCustomer"></span>');
                    }
                }

                //如果仅剩一行,那么不显示remove按钮
                if (this.$('.customerItem').length == 1) {
                    this.$('.removeCustomer').remove();
                }

            },

            onAddCustomer: function (e) {
                //移除添加按钮
                $(e.currentTarget).remove();
                //增加一行
                var rowEle = '<div class="customerItem"><span style="position: relative"><input type="text" class="customerName" placeholder="入住人姓名"></span><span> <select class=\"customerIdType\"><option value=\"IdCard\" selected=\"selected\">身份证</option></select> </span> <span><input type=\"text\" class=\"customerIdNo\" placeholder=\"证件号码\"></span></div>';
                this.$('.customerList').append($(rowEle));

                //大于一行的情况,末尾跟上移除按钮
                if (this.$('.customerItem').length > 1) {
                    this.$('.customerItem').each(function () {
                        if ($(this).find('.removeCustomer').length == 0) {
                            $(this).append('<span class="removeCustomer"></span>');
                        }
                    });
                }

                //在最后一行后面跟上添加按钮
                this.$('.customerItem:last').append('<span class="addCustomer"></span>');
                //自动将滚动条滚到最后
                $(".reserve-body").scrollTop($(".reserve-body").get(0).scrollHeight);
            },

            onTextboxFocus: function (e) {
                $(e.currentTarget).tooltip('hide');
                this.clearError($(e.currentTarget));
            },

            showError: function (target, wording, place) {
                //var $errMsg = $('#newRoomType .errorMsg');
                //$errMsg.html('*'+wording);
                if (!target.hasClass('validate-failed')) {
                    target.addClass('validate-failed');
                }

                place = (place === undefined || place.length === 0) ? 'top' : place; //默认为top

                target.tooltip({ 'trigger': 'manual', 'title': wording, 'placement': place });
                target.attr('data-original-title', wording).tooltip('show'); //不能直接target.tooltip('show'),文本替换无效
            },

            clearError: function (target) {
                //var $errMsg = $('#newRoomType .errorMsg');
                //$errMsg.html('');

                if (target.hasClass('validate-failed')) {
                    target.removeClass('validate-failed');
                }

                target.tooltip('hide');
            },

            render: function () {
                this.$el.html(this.template({ model: this.model, collection: this.options.collection }));
                return this;
            }
        });

        return newReserveView;
    });